package com.videoplayer;

import com.adapter.GridViewAdapter;
import com.adapter.SyncImageLoader;
import com.adsmogo.adview.AdsMogoLayout;
import com.application.VideosList;
import com.db.DBConnect;
import com.entity.YoukuVideo;
import com.html.FLVCDResolve;
import com.html.YoukuDetail;
import com.umeng.analytics.MobclickAgent;
import com.util.MyToast;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

public class VideoDetailActivity extends Activity implements OnClickListener {

	private final String DB_GET_SHARPNESS = "name = 'sharpness'";
	private final String DB_GET_ISQUICK = "name = 'quick_resolve'";
	private Button btnBack;
	private Button btnDownload;
	private String intentUrl;
	private String intentImg;
	private String intentTitle;
	private TextSwitcher tvDetailTitle;
	private ImageView ivDetailPic;
	private FLVCDResolve flvResolve;
	private VideosList videoList;
	private LinearLayout rlVideoList;
	private SyncImageLoader syncImageLoader;
	private HorizontalScrollView scrollCover;
	private GridView gvPackNumber;
	private boolean flag;
	private DBConnect dbCon;
	private RadioGroup rgKpi;
	private RadioButton rbLow;
	private RadioButton rbHigh;
	private RadioButton rbSuper;
	private int sharpnessFlag;
	private int dbSharpness;
	private int isQuick;
	private YoukuDetail youkuDetail;
	private Bundle b;
	private int size;
	private String webVideoUrl;
	private AdsMogoLayout adsMogoLayout;

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MobclickAgent.onError(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.video_detail_activity);
		dbCon = new DBConnect(this);
		youkuDetail = new YoukuDetail(this);
		syncImageLoader = new SyncImageLoader();
		btnBack = (Button) findViewById(R.id.btn_back);
		btnDownload = (Button) findViewById(R.id.btn_download);
		tvDetailTitle = (TextSwitcher) findViewById(R.id.tv_detail_title);
		tvDetailTitle.setFactory(new ViewFactory() {

			@Override
			public View makeView() {
				TextView tv = new TextView(VideoDetailActivity.this);
				tv.setTextColor(0xFF121212);
				tv.setTextSize(14);
				return tv;
			}
		});
		Animation in = AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in);
		Animation out = AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out);
		tvDetailTitle.setInAnimation(in);
		tvDetailTitle.setOutAnimation(out);
		adsMogoLayout = ((AdsMogoLayout) this.findViewById(R.id.adsMogoView));
		ivDetailPic = (ImageView) findViewById(R.id.iv_detail_pic);
		gvPackNumber = (GridView) findViewById(R.id.gv_packNumber);
		gvPackNumber.setSelector(new ColorDrawable(Color.TRANSPARENT));
		rlVideoList = (LinearLayout) findViewById(R.id.rl_video_list);
		scrollCover = (HorizontalScrollView) findViewById(R.id.sc_test);
		rgKpi = (RadioGroup) findViewById(R.id.rg_container);
		rgKpi.setOnCheckedChangeListener(onRadioGroupCheckChangeListener);
		rbLow = (RadioButton) findViewById(R.id.rb_low);
		rbHigh = (RadioButton) findViewById(R.id.rb_high);
		rbSuper = (RadioButton) findViewById(R.id.rb_super);
		flvResolve = new FLVCDResolve(this);
		webVideoUrl = getIntent().getExtras().getString("url");
		intentUrl = webVideoUrl;
		intentImg = getIntent().getExtras().getString("img");
		intentTitle = getIntent().getExtras().getString("title");
		syncImageLoader.loadImage(0, intentImg, imageLoadListener);
		tvDetailTitle.setText(intentTitle);
		dbCon.open();
		dbSharpness = dbCon.queryOneData(DB_GET_SHARPNESS);
		isQuick = dbCon.queryOneData(DB_GET_ISQUICK);
		dbCon.close();
		sharpnessFlag = dbSharpness;
		videoList = (VideosList) VideoDetailActivity.this
				.getApplicationContext();
		ivDetailPic.setOnClickListener(this);
		btnDownload.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		// DisplayMetrics metric = new DisplayMetrics();
		// getWindowManager().getDefaultDisplay().getMetrics(metric);
		// densityDpi = metric.densityDpi;
		new InitTaks().execute(intentUrl, sharpnessFlag + "");
	}

	RadioGroup.OnCheckedChangeListener onRadioGroupCheckChangeListener = new RadioGroup.OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			switch (checkedId) {
			case R.id.rb_low:
				sharpnessFlag = 0;
				changeButtons(0);
				break;
			case R.id.rb_high:
				sharpnessFlag = 1;
				changeButtons(1);
				break;
			case R.id.rb_super:
				sharpnessFlag = 2;
				changeButtons(2);
				break;
			default:
				break;
			}
		}
	};


	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	SyncImageLoader.OnImageLoadListener imageLoadListener = new SyncImageLoader.OnImageLoadListener() {

		@Override
		public void onImageLoad(Integer t, Drawable drawable) {
			// BookModel model = (BookModel) getItem(t);
			ivDetailPic = (ImageView) findViewById(R.id.iv_detail_pic);
			ivDetailPic.setBackgroundDrawable(drawable);
		}

		@Override
		public void onError(Integer t) {
			ivDetailPic = (ImageView) findViewById(R.id.iv_detail_pic);
			ivDetailPic.setBackgroundResource(R.drawable.detail_pic_loading);
		}

	};

	public class InitTaks extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {
			if (isQuick == 0) {
				flag = false;
				gvPackNumber.setVisibility(View.GONE);
				rbLow.setEnabled(false);
				rbHigh.setEnabled(false);
				rbSuper.setEnabled(false);
			} else {
				flag = false;
				gvPackNumber.setVisibility(View.GONE);
				rbLow.setVisibility(View.GONE);
				rbHigh.setVisibility(View.GONE);
				rbSuper.setVisibility(View.GONE);
			}
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			if (isQuick == 0) {
				flvResolve.getPlayUrl(params[0], params[1]);
				return params[0];
			} else {
				flvResolve.getPlayUrl(params[0], params[1], dbSharpness);
				return params[0];
			}
		}

		@Override
		protected void onPostExecute(String result) {
			if (isQuick == 0) {
				rbLow.setEnabled(true);
				rbHigh.setEnabled(true);
				rbSuper.setEnabled(true);
				dbCon.open();
				setDefaultSharpness(dbCon.queryOneData(DB_GET_SHARPNESS));
				dbCon.close();
				Log.v("intentUrl","++++++++++++"+result);
				if (result.contains("youku")) {
					new getMoreInfoTask().execute(result);
					Log.v("intentUrl","youku"+result);
				} else if (result.contains("v.qq")) {
					new getTecentMoreInfoTask().execute(result);
					Log.v("intentUrl","qq"+result);
				}
			} else {
				quickSetSharpness();
				flag = true;
			}
			super.onPostExecute(result);
		}

	}

	public class getMoreInfoTask extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... arg0) {
			return youkuDetail.getYoukuDetailInfo(arg0[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			if(videoList.getPackNumber().size()>0){
				adsMogoLayout.setADEnable(true);
			}
			gvPackNumber.setVisibility(View.VISIBLE);
			flag = true;
			if (!"".equals(videoList.getYoukuDetailTitle())) {
				tvDetailTitle.setText(videoList.getYoukuDetailTitle());
			}
			GridViewAdapter gdViewAdapter = new GridViewAdapter(
					VideoDetailActivity.this, videoList.getPackNumber());
			gvPackNumber.setAdapter(gdViewAdapter);
			gdViewAdapter.notifyDataSetChanged();
			gvPackNumber.setOnItemClickListener(packNumberItemClickListener);
			super.onPostExecute(result);
		}
	}
	
	public class getTecentMoreInfoTask extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... arg0) {
			return youkuDetail.getTecentDetailInfo(arg0[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			gvPackNumber.setVisibility(View.VISIBLE);
			flag = true;
//			if (!"".equals(videoList.getYoukuDetailTitle())) {
//				tvDetailTitle.setText(videoList.getYoukuDetailTitle());
//			}
			GridViewAdapter gdViewAdapter = new GridViewAdapter(
					VideoDetailActivity.this, videoList.getPackNumber());
			gvPackNumber.setAdapter(gdViewAdapter);
			gdViewAdapter.notifyDataSetChanged();
			gvPackNumber.setOnItemClickListener(packNumberItemClickListener);
			super.onPostExecute(result);
		}
	}

	OnItemClickListener packNumberItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			intentUrl = videoList.getPackNumber().get(arg2).getUrl();
			new InitTaks().execute(
					videoList.getPackNumber().get(arg2).getUrl(), sharpnessFlag
							+ "");
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		videoList.resetYoukuDetailTitle();
		if (videoList.getRealLowUrlArray() != null)
			videoList.getRealLowUrlArray().clear();
		if (videoList.getRealHighUrlArray() != null)
			videoList.getRealHighUrlArray().clear();
		if (videoList.getRealSuperUrlArray() != null)
			videoList.getRealSuperUrlArray().clear();
	}

	public void changeButtons(int sharpness) {
		rlVideoList.removeAllViews();
		int count = 0;
		if (0 == isQuick) {
			if (videoList.getRealLowUrlArray() != null) {
				switch (sharpness) {
				case 0:
					count = videoList.getRealLowUrlArray().size();
					break;
				case 1:
					count = videoList.getRealHighUrlArray().size();
					break;
				case 2:
					count = videoList.getRealSuperUrlArray().size();
					break;
				default:
					count = videoList.getRealLowUrlArray().size();
					break;

				}
			}
		} else {
			count = size;
		}
		if(count<1){
			MyToast toast = new MyToast(this, "该视频无法为您播放",3000);
			toast.show();
			ivDetailPic.setOnClickListener(null);
			btnDownload.setOnClickListener(null);
			return;
		}
		ivDetailPic.setOnClickListener(this);
		for (int i = 0; i < count; i++) {
			Button btn = new Button(VideoDetailActivity.this);
			final int tmp = i;
			btn.setText(i + 1 + "");
			btn.setBackgroundColor(0xFF1399f8);
			int height = (int) (TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 37, VideoDetailActivity.this
							.getResources().getDisplayMetrics()));
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, height);
			lp.setMargins(22, 0, 0, 0);
			LinearLayout.LayoutParams lpr = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, height);
			lpr.setMargins(22, 0, 22, 0);
			if (i == (count - 1)) {
				btn.setLayoutParams(lpr);
			} else {
				btn.setLayoutParams(lp);
			}
			btn.setTextColor(0xffFFFFFF);
			btn.setGravity(Gravity.CENTER);
			btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					gotoPlayActivity(tmp);
				}
			});
			rlVideoList.addView(btn);

		}
	}

	public void quickSetSharpness() {
		if (videoList.getRealLowUrlArray() != null
				&& videoList.getRealLowUrlArray().size() > 0) {
			size = videoList.getRealLowUrlArray().size();
			rbLow.setVisibility(View.VISIBLE);
			rbLow.setChecked(true);
		} else if (videoList.getRealHighUrlArray() != null
				&& videoList.getRealHighUrlArray().size() > 0) {
			size = videoList.getRealHighUrlArray().size();
			rbHigh.setVisibility(View.VISIBLE);
			rbHigh.setChecked(true);
		} else {
			size = videoList.getRealSuperUrlArray().size();
			rbSuper.setVisibility(View.VISIBLE);
			rbSuper.setChecked(true);
		}
	}

	public void setDefaultSharpness(int sharpness) {
		if (videoList.getSharpness() == 0) {
			rbLow.setChecked(true);
			sharpnessFlag = 0;
			rbHigh.setVisibility(View.INVISIBLE);
			rbSuper.setVisibility(View.INVISIBLE);
		} else if (videoList.getSharpness() == 1 && sharpness >= 1) {
			rbHigh.setChecked(true);
			rbSuper.setVisibility(View.INVISIBLE);
			sharpnessFlag = 1;
		} else {
			switch (sharpness) {
			case 0:
				rbLow.setChecked(true);
				sharpnessFlag = 0;
				break;
			case 1:
				rbHigh.setChecked(true);
				sharpnessFlag = 1;
				break;
			case 2:
				rbSuper.setChecked(true);
				sharpnessFlag = 2;
				break;
			default:
				break;
			}
		}
	}

	@TargetApi(8)
	public void gotoPlayActivity(int start) {
		if (flag) {

			b = new Bundle();
			String[] finalUrl = null;
			int k = 0;
			int t = 0;
			switch (sharpnessFlag) {
			case 0:
				finalUrl = new String[videoList.getRealLowUrlArray().size()];
				t = videoList.getRealLowUrlArray().size();
				for (int j = start; j < videoList.getRealLowUrlArray().size(); j++) {
					String videoUrl = videoList.getRealLowUrlArray().get(j)
							.toString();
					if (j < videoList.getRealLowUrlArray().size()) {
						finalUrl[k] = videoUrl.substring(
								videoUrl.indexOf("http:"),
								videoUrl.lastIndexOf("target") - 2);
						k++;
					}
				}
				break;
			case 1:
				finalUrl = new String[videoList.getRealHighUrlArray().size()];
				t = videoList.getRealHighUrlArray().size();
				for (int j = start; j < videoList.getRealHighUrlArray().size(); j++) {
					String videoUrl = videoList.getRealHighUrlArray().get(j)
							.toString();
					if (j < videoList.getRealHighUrlArray().size()) {
						finalUrl[k] = videoUrl.substring(
								videoUrl.indexOf("http:"),
								videoUrl.lastIndexOf("target") - 2);
						k++;
					}
				}
				break;
			case 2:
				finalUrl = new String[videoList.getRealSuperUrlArray().size()];
				t = videoList.getRealSuperUrlArray().size();
				for (int j = start; j < videoList.getRealSuperUrlArray().size(); j++) {
					String videoUrl = videoList.getRealSuperUrlArray().get(j)
							.toString();
					if (j < videoList.getRealSuperUrlArray().size()) {
						finalUrl[k] = videoUrl.substring(
								videoUrl.indexOf("http:"),
								videoUrl.lastIndexOf("target") - 2);
						k++;
					}
				}
				break;
			default:
				finalUrl = new String[videoList.getRealLowUrlArray().size()];
				t = videoList.getRealLowUrlArray().size();
				for (int j = start; j < videoList.getRealLowUrlArray().size(); j++) {
					String videoUrl = videoList.getRealLowUrlArray().get(j)
							.toString();
					if (j < videoList.getRealLowUrlArray().size()) {
						finalUrl[k] = videoUrl.substring(
								videoUrl.indexOf("http:"),
								videoUrl.lastIndexOf("target") - 2);
						k++;
					}
				}
				break;
			}

			b.putCharSequenceArray("href", finalUrl);
			if (!"Bundle[{}]".equals(b.toString())) {
				Intent intent = new Intent();
				intent.setClass(VideoDetailActivity.this, testVideoPlayer.class);
				intent.putExtra("url", b);
				intent.putExtra("totle", t);
				intent.putExtra("current", start + 1);
				if (isQuick == 0) {
					if (!"".equals(videoList.getYoukuDetailTitle())) {
						intent.putExtra("title",
								videoList.getYoukuDetailTitle());
					} else {
						intent.putExtra("title", intentTitle);
					}
				} else {
					intent.putExtra("title", intentTitle);
				}
				intent.putExtra("vUrl", webVideoUrl);
				intent.putExtra("img", intentImg);
				startActivity(intent);
			} else {
				MyToast toast = new MyToast(this, "该视频无法为您播放");
				toast.show();
			}
		} else {
			MyToast toast = new MyToast(this, "请稍后,正在解析");
			toast.show();
			// Toast.makeText(this, "请等待播放地址解析....", 1000).show();
		}
	}

	@SuppressLint("NewApi")
	private Bundle anylize() {
		Bundle b = new Bundle();
		String[] finalUrl = null;
		switch (sharpnessFlag) {
		case 0:
			finalUrl = new String[videoList.getRealLowUrlArray().size()];
			for (int j = 0; j < videoList.getRealLowUrlArray().size(); j++) {
				String videoUrl = videoList.getRealLowUrlArray().get(j)
						.toString();
				finalUrl[j] = videoUrl.substring(videoUrl.indexOf("http:"),
						videoUrl.lastIndexOf("target") - 2);
			}
			break;
		case 1:
			finalUrl = new String[videoList.getRealHighUrlArray().size()];
			for (int j = 0; j < videoList.getRealHighUrlArray().size(); j++) {
				String videoUrl = videoList.getRealHighUrlArray().get(j)
						.toString();
				finalUrl[j] = videoUrl.substring(videoUrl.indexOf("http:"),
						videoUrl.lastIndexOf("target") - 2);
			}
			break;
		case 2:
			finalUrl = new String[videoList.getRealSuperUrlArray().size()];
			for (int j = 0; j < videoList.getRealSuperUrlArray().size(); j++) {
				String videoUrl = videoList.getRealSuperUrlArray().get(j)
						.toString();
				finalUrl[j] = videoUrl.substring(videoUrl.indexOf("http:"),
						videoUrl.lastIndexOf("target") - 2);
			}
			break;
		default:
			finalUrl = new String[videoList.getRealLowUrlArray().size()];
			for (int j = 0; j < videoList.getRealLowUrlArray().size(); j++) {
				String videoUrl = videoList.getRealLowUrlArray().get(j)
						.toString();
				finalUrl[j] = videoUrl.substring(videoUrl.indexOf("http:"),
						videoUrl.lastIndexOf("target") - 2);
			}
			break;
		}

		b.putCharSequenceArray("href", finalUrl);
		return b;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_detail_pic:
			gotoPlayActivity(0);
			break;
		case R.id.btn_back:
			this.finish();
			break;
		case R.id.btn_download:
			if (flag) {
				Intent intent = new Intent();
				String tempTitle = "";
				intent.setClass(VideoDetailActivity.this,
						DownLoadActivity.class);
				if (null == videoList.getYoukuDetailTitle()
						|| "".equals(videoList.getYoukuDetailTitle())) {
					tempTitle = intentTitle;
				} else {
					tempTitle = videoList.getYoukuDetailTitle();
				}
				// if (isQuick == 0) {
				// if (!"".equals(videoList.getYoukuDetailTitle())) {
				// intent.putExtra("title",
				// videoList.getYoukuDetailTitle());
				// } else {
				// intent.putExtra("title", intentTitle);
				// }
				// } else {
				//
				// }
				intent.putExtra("title", tempTitle);
				intent.putExtra("vUrl", webVideoUrl);
				intent.putExtra("url", anylize());

				if (null == anylize()) {
					MyToast toast = new MyToast(this, "该视频无法播放");
					toast.show();
					break;
				}
				intent.putExtra("img", intentImg);
				startActivity(intent);
			} else {
				MyToast toast = new MyToast(this, "请稍后,正在解析");
				toast.show();
			}
			break;
		default:
			break;
		}
	}
}
